<template>
    <div class="detail">
        <!-- 操作栏 -->
        <operation :formData="formData.channel" @save="save" />
        <!-- 表格列表 -->
        <formlist
            ref="formlist"
            :formList="formList"
            :formData="formData.channel"
            :status="v_status"
            :disabled="v_disabled"
            class="form-module mgt-12"
        />
        <authority-tab :tabMapOptions="anchorList">
            <!-- 渠道属性 -->
            <template v-slot:channelProperties="{ item }">
                <channel-group
                    ref="channelGroup"
                    :channelFormData="formData.channel"
                    :channelFormList="channelFormList"
                    :status="v_status"
                    :disabled="item.edit ? v_disabled : true"
                >
                    <template v-slot:title>
                        <base-title :ref="item.ref" :title="$t(item.lang)" />
                    </template>
                </channel-group>
            </template>
            <!--商城字段-->
            <template v-slot:mallField="{ item }">
                <mall-field :disabled="item.edit ? v_disabled : true" :formData="formData.channel" :formList="mallFieldFormList">
                    <template v-slot:title>
                        <base-title :ref="item.ref" :title="$t(item.lang)" />
                    </template>
                </mall-field>
            </template>
            <template v-slot:channel_page_finance="{ item }">
                <!-- 财务信息 -->
                <finance-group
                    ref="financeGroup"
                    :financeFormData="formData.channel"
                    :disabled="item.edit ? v_disabled : true"
                    :status="v_status"
                    :financeFormList="financeFormList"
                >
                    <template v-slot:title>
                        <base-title :ref="item.ref" :title="$t(item.lang)" />
                    </template>
                </finance-group>
            </template>
            <template v-slot:address="{ item }">
                <channel-address :channelReceiveInfoList="formData.channelReceiveInfoList" :disabled="item.edit ? v_disabled : true">
                    <template v-slot:title>
                        <base-title :ref="item.ref" :title="$t(item.lang)" />
                    </template>
                </channel-address>
            </template>
            <!--      <template v-slot:channel_page_sale_policy="{item}">-->
            <!--        <sale-policy-->
            <!--          :disabled="item.edit ? v_disabled: true"-->
            <!--          :saleTableData="formData.channelSaleDiscountList">-->
            <!--          <template v-slot:title>-->
            <!--            <base-title-->
            <!--              :ref="item.ref"-->
            <!--              :title="$t(item.lang)" />-->
            <!--          </template>-->
            <!--        </sale-policy>-->
            <!--      </template>-->
            <template v-slot:channel_page_setting="{ item }">
                <control-config
                    :key="render"
                    ref="settingOptions"
                    :channelSettings="channelSettings"
                    :configFormData="configFormData"
                    :disabled="v_disabled"
                >
                    <template v-slot:title>
                        <base-title :ref="item.ref" :title="$t(item.lang)" />
                    </template>
                </control-config>
            </template>
        </authority-tab>
        <!-- 自定义的字段 -->
        <div v-for="item in customerFieldsTabs" :key="item.value">
            <customer-tabs
                :key="item.value"
                :ref="item.ref"
                :disabled="v_disabled"
                :status="v_status"
                :tabTitle="item.label"
                :formList="item.formList"
                :customerFormdata="formData.channel"
            />
        </div>

        <!-- 锚点导航 -->
        <base-anchor :element="$refs" :anchor="anchorList" />
    </div>
</template>

<script lang="ts">
// import Vue from 'vue'
import Component, { mixins } from 'vue-class-component';
import { detailConfig, tabsConfig, initFormData } from './configs';
import { Watch } from 'vue-property-decorator';
import vuexMixins from '@/mixins/vuex-modulel-mixins';
import detailMixins from '@/mixins/detail-mixins';
import apiUrl from '@/api/config-center/channelOrganization';
import { Dictionary, AnchorConfig } from '@/typings';
import { transformFields } from '@/utils';
import { Tools } from '@/utils/tools';
const FIX_PROPS_TABS = {
    channel_property: 'channelFormList',
    channel_finance: 'financeFormList'
};
const SHOW_TYPE = {
    '1': 'input',
    '2': 'number',
    '3': 'datePick',
    '4': 'checkbox',
    '5': 'select',
    '6': 'mulitSelect'
};
@Component({
    name: 'channelOrganization-detail',
    components: {
        operation: () => import('./operation.vue'),
        formlist: () => import('@/components/formlist/index.vue'),
        baseTitle: () => import('@/components/base-title/index.vue'),
        baseAnchor: () => import('@/components/base-anchor/index.vue'),
        channelGroup: () => import('./tabs/channel-group.vue'),
        salePolicy: () => import('./tabs/sale-group.vue'),
        customerTabs: () => import('@/layout-components/customer-fields-tab/index.vue'),
        financeGroup: () => import('./tabs/finance-group.vue'),
        treeFolder: () => import('./tabs/tree-folder.vue'),
        controlConfig: () => import('./tabs/control-config.vue'),
        channelAddress: () => import('./tabs/address.vue'),
        authorityTab: () => import('@/layout-components/authority-tab/index.vue'),
        mallField: () => import('./tabs/mall-field.vue')
    }
})
export default class detail extends mixins(detailMixins, vuexMixins) {
    formList = detailConfig.formList;
    formData: Dictionary<any> = initFormData();
    channelFormList = tabsConfig.channelProperties;
    financeFormList = tabsConfig.financialInformation;
    mallFieldFormList = tabsConfig.mallField;
    customerFieldsTabs: any[] = [];
    anchorList: AnchorConfig[] = tabsConfig.anchorConfig;
    channelSettings: any[] = [];
    configFormData: Dictionary = {};
    render: number = 0;
    @Watch('v_id', { immediate: true })
    onRolesDetailIdChanged(val, oldval) {
        if (val && val !== oldval) {
            Tools.debounce(this.viewDetail(val.split('_')[0]), 50);
        }
    }

    @Watch('v_status')
    onv_statusChange(val) {
        if (['add', 'cancel'].includes(val)) this.reset();
    }
    created() {
        this.getModuleCustomerFileds();
        this.$nextTick(() => {
            this.getSettingConfig();
        });
    }
    /**
     * 获得渠道档案详情
     */
    async viewDetail(id: string) {
        const res = await this._get({
            url: apiUrl.getChannelDetail + id
        });
        if (res.code === 0) {
            const { customFieldMap, channelSettingList, channelReceiveInfoList, businessLicense, ...other } = res.data;
            // this.formData = Object.assign({channel:other}, customFieldMap)
            const area: number[] = [other.nation, other.region, other.province, other.city, other.county].filter((e) => e);
            const organization: number[] = [
                other.organization1,
                other.organization2,
                other.organization3,
                other.organization4,
                other.organization5
            ].filter((e) => e);
            this.updateSetting(channelSettingList);
            this.formData = Object.assign(
                {},
                {
                    channel: Object.assign(
                        {
                            area,
                            organization,
                            businessLicense: [businessLicense]
                        },
                        other,
                        customFieldMap
                    )
                },
                {
                    customFieldMap,
                    channelReceiveInfoList: channelReceiveInfoList || []
                }
            );
            console.log(this.formData);

            this.$store.dispatch(`${this.m_moduleId}/v_setBtnsAuth`, other.status + '');
        }
    }
    async getModuleCustomerFileds() {
        this.customerFieldsTabs = [];
        // 获取自定义字段和分类
        await this.m_getModuleCustomerFiledsFn(FIX_PROPS_TABS, this.formData, this.m_moduleId);
    }
    updateSetting(data) {
        this.channelSettings = data;
        this.formatTreeList(this.channelSettings);
    }
    async getSettingConfig() {
        const res = await this._post({
            url: apiUrl.getChannelSetting,
            data: { user: '' }
        });
        if (res.code === 0) {
            this.updateSetting(res.data);
        }
    }
    formatTreeList(arr) {
        arr.forEach((item) => {
            if (item.parentId !== 0) {
                // 子类
                item.channelSettingValues &&
                    item.channelSettingValues.forEach((values, index) => {
                        if (values === 'true') {
                            item.channelSettingValues[index] = true;
                        }
                        if (values === 'false') {
                            item.channelSettingValues[index] = false;
                        }
                    });
                item.channelSettingDataLists =
                    item.channelSettingDataLists &&
                    transformFields(item.channelSettingDataLists, {
                        label: 'title',
                        value: 'id'
                    }).map((item) => {
                        item.value = item.value.toString();
                        return item;
                    });
                item.dataType = SHOW_TYPE[item.dataType.toString()];
                this.$set(this.configFormData, item.keyCode, item.channelSettingValues ? item.channelSettingValues : []);
            }
            item.childChannelSetting && this.formatTreeList(item.childChannelSetting);
        });
    }
    /**
     * 保存
     */
    async save() {
        // 校验表头字段
        await (this.$refs.formlist as any).saveTable();
        this.$refs.channelGroup && (await (this.$refs.channelGroup as any).$refs.formlist.saveTable());
        this.$refs.financeGroup && (await (this.$refs.financeGroup as any).$refs.formlist.saveTable());
        // 校验自定义分类的字段必填
        for (const item of this.customerFieldsTabs) {
            await (this.$refs[item.ref][0] as any).$refs.formlist.saveTable();
        }
        const confirmText = this.$t('dialogPrompt.save');
        this._confirm({ content: confirmText })
            .then(async () => {
                const formData = JSON.parse(JSON.stringify(this.formData));
                const { customFieldMap, languageMap, channelReceiveInfoList, channel } = formData;
                // 把固定tab的自定义字段值都放到  customFieldMap 中
                for (const key in customFieldMap) {
                    if (Object.keys(formData).includes(key)) {
                        customFieldMap[key] = channel[key];
                        delete channel[key];
                    }
                }
                delete channel.area;
                delete channel.organization;
                let filterchannelReceiveInfos = [];
                if (channelReceiveInfoList) {
                    filterchannelReceiveInfos = channelReceiveInfoList.filter((item) => !item.edit);
                }
                const channelSettingSaveParams: any[] = Object.keys(this.configFormData).map((item) => {
                    return {
                        keyCode: item,
                        values: this.configFormData[item] ? [].concat(this.configFormData[item]) : ['']
                    };
                });
                const saveData = {
                    data: Object.assign({ languageMap }, channel, {
                        customFieldMap,
                        // channelSettingSaveParams,
                        channelReceiveInfoList: filterchannelReceiveInfos,
                        channelSettingList: channelSettingSaveParams.map((em) => {
                            return {
                                channelSettingValues: em['values'],
                                keyCode: em['keyCode']
                            };
                        }),
                        businessLicense: channel.businessLicense.length && Array.isArray(channel.businessLicense) ? channel.businessLicense[0] : null
                    })
                };
                const url = this.v_status === 'add' ? apiUrl.addChannel : apiUrl.updateChannel;
                const res = this.v_status === 'add' ? await this._post({ url, data: saveData }) : await this._put({ url, data: saveData });

                if (res.code === 0) this.m_dealSaveAction(res);
            })
            .catch(() => {});
    }

    /**
     * 重置
     */
    reset() {
        this.m_reset('channel');
        Object.keys(this.configFormData).forEach((item) => {
            if (Array.isArray(item) && item[0] === true) {
                item[0] = false;
            } else {
                this.$set(this.configFormData, item, []);
            }
        });
        this.render++;
    }
}
</script>

<style scoped lang="scss">
@import 'src/styles/variables.scss';
.detail {
    background: #fff;
}
.tree-list {
    border-bottom: 1px solid #eee;
}
.config-list {
    padding-bottom: 15px;
    // min-height: calc(100vh - 148px);
    &-box {
        height: auto;
        transition: height 0.5s ease;
    }
    &-header {
        height: 28px;
        line-height: 28px;
        display: flex;
        font-size: 12px;
        border: 1px solid #eee;
        border-bottom: none;
    }
    .common-placeholder {
        width: 32px;
        line-height: 28px;
        text-align: center;
        transition: all 0.5s;
    }
    .bg-e {
        background: #eee;
    }
}
.no-data {
    min-height: calc(100vh - 200px);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    /* height: min-content; */
    color: $colorTextPlaceholder;
    flex: 1;
    border: 1px solid #eee;
    &-img {
        width: 80px;
        height: 80px;
        margin-bottom: 10px;
    }
}
</style>
